package du.myseckill.service.Impl;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import du.myseckill.dto.SecKillMsg;
import du.myseckill.dto.SeckillExcecution;
import du.myseckill.enums.SecKillStatEnum;
import du.myseckill.exception.ServerException;
import du.myseckill.service.GoodsService;
import du.myseckill.vo.SecKillResult;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static du.myseckill.Const.RedisPrefix.GOODS_NUMBER;

/**
 * 过期秒杀消息消费者，消费消息队列中的过期秒杀操作消息
 */
@Component
@RabbitListener(queues = {"secKill_dead_queue"})
public class SecKillMQDeadConsumer {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitHandler
    public void secKillDeadConsumer(String msg, Channel channel,
                                @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws ServerException, IOException {
        SecKillMsg secKillMsg = JSON.parseObject(msg, SecKillMsg.class);
        try {
            //查缓存库存
            Integer number = JSON.parseObject(JSON.toJSONString(redisTemplate.boundValueOps(GOODS_NUMBER + secKillMsg.getGoodsId()).get()),Integer.class
            );
            //库存为0
            if(number!=null&&number==0){
                SecKillResult secKillResult = new SecKillResult(true, new SeckillExcecution(secKillMsg.getGoodsId(), SecKillStatEnum.END));
                //利用websocket将秒杀结果返回给用户
                WebSocketServer.sendInfo(secKillResult, secKillMsg.getUserId().toString());
            }else{
                //库存不为0
                SeckillExcecution seckillExcecution = goodsService.executeSecKillDBPLock(secKillMsg.getGoodsId(), secKillMsg.getUserId(), secKillMsg.getUserPhone(), secKillMsg.getMd5());
                WebSocketServer.sendInfo(new SecKillResult<>(true,seckillExcecution), secKillMsg.getUserId().toString());
            }
           channel.basicAck(tag,false);
        }catch (Exception e){
            SecKillResult secKillResult = new SecKillResult(true, new SeckillExcecution(secKillMsg.getGoodsId(), SecKillStatEnum.INNER_ERROR));
            //利用websocket将秒杀结果返回给用户
            WebSocketServer.sendInfo(secKillResult, secKillMsg.getUserId().toString());
            channel.basicNack(tag,false,false);
            e.printStackTrace();
        }
    }

}
